package com.ebelter.scaleblesdk;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import com.ebelter.scaleblesdk.ble.bluetooth.BlueToothMessageListener;
import com.ebelter.scaleblesdk.ble.bluetooth.callback.BleSatusCallback;
import com.ebelter.scaleblesdk.ble.bluetooth.callback.ConnectCallback;
import com.ebelter.scaleblesdk.ble.bluetooth.callback.FirmwareUpgradeCallback;
import com.ebelter.scaleblesdk.ble.bluetooth.callback.ScanResultCallback;
import com.ebelter.scaleblesdk.ble.bluetooth.device.WeightDataHandle;
import com.ebelter.scaleblesdk.ble.bluetooth.impl.IDeviceAlarmCallback;
import com.ebelter.scaleblesdk.ble.bluetooth.impl.IDeviceCommandCallback;
import com.ebelter.scaleblesdk.ble.bluetooth.impl.IDeviceConnectCallback;
import com.ebelter.scaleblesdk.ble.bluetooth.impl.IMeasureResultCallback;
import com.ebelter.scaleblesdk.ble.bluetooth.OnDeviceConnectedListener;
import com.ebelter.scaleblesdk.ble.bluetooth.impl.IUserInfoChangedCallback;
import com.ebelter.scaleblesdk.ble.bluetooth.impl.WeightMessage;
import com.ebelter.scaleblesdk.common.Fields;
import com.ebelter.scaleblesdk.common.FileNames;
import com.ebelter.scaleblesdk.helper.SharePrefrenceHelper;
import com.ebelter.scaleblesdk.model.FileType;
import com.ebelter.scaleblesdk.model.ScaleUser;
import com.ebelter.scaleblesdk.ble.model.UserCommand;
import com.ebelter.scaleblesdk.ble.upgrade.FirmwareUpgrader;
import com.ebelter.scaleblesdk.util.SystemTool;
import com.ebelter.scaleblesdk.util.ULog;


/**
 * @author 作 者：pan
 * @filename 文件名：ScaleBleManager.java
 * @description 描 述：体脂秤蓝牙管理器
 * @date 时 间：2017-11-3
 * @Copyright 版 权：倍泰源代码，版权归深圳市倍泰健康测量分析技术有限公司所有。
 */
public class ScaleBleManager {

    private static final String TAG = "ScaleBleManager";
    private static int REQUEST_ENABLE_BT = 101;

    private static ScaleBleManager instance;

    private static BlueToothMessageListener btMsgListener;
    private static WeightDataHandle weightDataHandler;
    private static WeightMessage mWeightMessage;
    private static Activity mActivity;
    private BluetoothDevice curDevice;
    private ScaleUser curUser;
    public ScanResultCallback mScanResultCallback;
    public ConnectCallback mConnectCallback;
    public ConnectStatus mConnectStatus = ConnectStatus.DISCONNECTED;

    private ScaleBleManager() {
    }

    /**
     * 1. 初始化蓝牙模块
     *
     * @param aty
     */
    public static void init(Activity aty) {
        if (aty == null) {
            return;
        }
        mActivity = aty;
        if (instance == null) {

            instance = new ScaleBleManager();
            //打开蓝牙
            open(aty);

            ScaleUser.getUser().setMac(SystemTool.genertMac(aty));

            //创建实例
            mWeightMessage = new WeightMessage();
            weightDataHandler = new WeightDataHandle(mWeightMessage);
            btMsgListener = BlueToothMessageListener.getInstance(aty.getApplicationContext(), weightDataHandler);

            //初始化固件升级工具， 暂不提供
            FirmwareUpgrader mFirmwareUpgrader = FirmwareUpgrader.getInstance();
            mWeightMessage.setFirmwareUpgradeCallback(mFirmwareUpgrader.getFirmwareUpgradeCallback());
            mFirmwareUpgrader.init(aty.getApplicationContext(), weightDataHandler);

            //设置监听器
            mWeightMessage.setOnWriteDataListener(new WeightMessage.OnWriteDataListener() {
                @Override
                public void onWriteData(byte[] data) {
                    btMsgListener.writeLlsAlertLevel(data);
                }
            });

            btMsgListener.setOnDeviceConnectedListener(new OnDeviceConnectedListener() {
                @Override
                public void onDeviceConnected(BluetoothDevice device) {
                    instance.curDevice = device;
                    if (instance.mConnectCallback != null) {
                        instance.mConnectCallback.onConnected(device);
                    }
                }
            });

            mWeightMessage.setOnDeleteAllUserListener(new WeightMessage.OnDeleteAllUserListener() {
                @Override
                public void onDeleteAllUser() {
                    btMsgListener.disConnectDevice();
                    btMsgListener.startConnectDevice(instance.curDevice);
                }
            });
            mWeightMessage.setOnReceiveMeasureResultListener(new WeightMessage.OnReceiveMeasureResultListener() {
                @Override
                public void onReceiveMeasureResult() {
                    instance.sendUserInfo(ScaleUser.getUser());
                }

                @Override
                public void onReceiveHistoryResult() {
                    //下发信息，告诉秤，已经接到离线数据
                    if (weightDataHandler != null) {
                        weightDataHandler.sendGetRecordAck();
                    }
                }
            });
//            //已绑定设备开始扫描
//            if (instance.isDeviceBound(aty.getApplicationContext())) {
//                instance.startScan();
//            }

            //注册息屏监听广播
            instance.registSreenStatusReceiver();
        }
    }


    /**
     * 2. 打开蓝牙

     */
    public static void open(Activity aty) {

        if (aty == null) {
            return;
        }
        // Initializes Bluetooth adapter.
        final BluetoothManager bluetoothManager = (BluetoothManager) aty.getSystemService(Context.BLUETOOTH_SERVICE);
        BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter();
        ULog.i(TAG, "---open---mBluetoothAdapter = " + mBluetoothAdapter);
        // Ensures Bluetooth is available on the device and it is enabled. If not,
        // displays a dialog requesting user permission to enable Bluetooth.
        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            aty.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
        ULog.i(TAG, "---open---isEnabled = " + mBluetoothAdapter.isEnabled());
    }

    public static synchronized ScaleBleManager getInstance() {
        return instance;
    }


    /**
     * 注册ConnectCallback连接监听回调
     */
    public void registerConnectCallback(ConnectCallback callback) {
        this.mConnectCallback = callback;
    }

    /**
     * 注册IUserInfoChangedCallback秤用户信息改变监听回调
     */
    public void registerUserInfoChangedCallback(IUserInfoChangedCallback callback) {
        mWeightMessage.setUserInfoChangedCallback(callback);
    }

    /**
     * 注册IMeasureResultCallback测量结果监听回调

     */
    public void registerMeasureResultCallback(IMeasureResultCallback callback) {
        if (mWeightMessage != null) {
            mWeightMessage.setMeasureResultCallback(callback);
        }
    }

    /**
     * 注册IFirmwareUpdateCallback固件升级监听回调
     */
    public void registerFirmwareUpgradeCallback(FirmwareUpgradeCallback callback) {
        if (mWeightMessage != null) {
            FirmwareUpgrader.getInstance().registerFirmwareUpgradeCallback(callback);
        }
    }

    /**
     * 注册BleSatusCallback 手机蓝牙状态改变监听
     */
    public void registerBleSatusCallback(BleSatusCallback callback) {
        btMsgListener.setBleSatusCallback(callback);
    }


    public void registerDeviceCommandCallback(IDeviceCommandCallback callback) {
        if (mWeightMessage != null) {
            mWeightMessage.setDeviceCommandCallback(callback);
        }
    }


    public void registerDeviceAlarmCallback(IDeviceAlarmCallback callback) {
        if (mWeightMessage != null) {
            mWeightMessage.setDeviceAlarmCallback(callback);
        }
    }

    /**
     * 3. 扫描设备
     */
    public void startScan(ScanResultCallback callback) {
        if (mWeightMessage != null) {
            this.mScanResultCallback = callback;
            mWeightMessage.setDeviceConnectCallback(scanResultCallback);
            btMsgListener.startScanDevice();
        }
    }

    public void setScanTimeout(int millis){
        if (btMsgListener!=null)btMsgListener.setScanTimeout(millis);
    }

    public void startScan() {
        if (mWeightMessage != null) {
            mWeightMessage.setDeviceConnectCallback(scanResultCallback);
            btMsgListener.startScanDevice();
        }
    }

    public void stopScan() {
        if (btMsgListener != null) {
            btMsgListener.stopScanDevice();
        }
    }



    /**
     * 4. 绑定设备
     */
    public void startConnect(BluetoothDevice device) {
        if (btMsgListener != null) {
            btMsgListener.startConnectDevice(device);
        }
    }
    public void startConnect(String deviceAddress) {
        startConnect(BluetoothAdapter.getDefaultAdapter().getRemoteDevice(deviceAddress));
    }
    /**
     * 5. 解绑设备
     */
    public void unbindDevice() {
        if (btMsgListener != null) {
            btMsgListener.unbindDevice();
        }
    }

    /**
     * 6. 断开连接
     */
    public void disConnectDevice() {
        if (btMsgListener != null) {
            btMsgListener.disConnectDevice();
        }
    }

    /**
     * 是否已绑定体脂秤
     *
     * @param ctx
     * @return
     */
    public boolean isDeviceBound(Context ctx) {
        //读取绑定的设备的mac
        SharePrefrenceHelper spf = new SharePrefrenceHelper(ctx);
        spf.open(FileNames.STRING_FILE);
        String mac = spf.getString(Fields.DEVICE_MAC);
        return mac != null;
    }

    /**
     * 7. 下发用户信息
     *
     * @param user
     */
    public void sendUserInfo(ScaleUser user) {
        if (weightDataHandler != null) {
            this.curUser = user;
            mWeightMessage.setUserCommand(UserCommand.SEND_USER_INFO);
            weightDataHandler.sendUserInfo(user);
        }
    }

    /**
     * 8. 清除用户信息
     */
    public void sendDelAllUser() {
        if (weightDataHandler != null) {
            mWeightMessage.setUserCommand(UserCommand.DELETE_ALL_USER);
            weightDataHandler.sendDelAllUser();
        }
    }

    /**
     * 9. 请求离线数据
     */
    public void requestOfflineData(String btId) {
        if (weightDataHandler != null) {
            weightDataHandler.sendGetRecord(btId);
        }
    }

    /**
     * 10. 获取固件版本
     */
    public void requestFirmwareVersion() {
        ULog.i(TAG, "----------requestFirmwareVersion-----------");
        if (weightDataHandler != null) {
            weightDataHandler.sendUserInfo(ScaleUser.getUser());
            weightDataHandler.sendGetVersion();
        }
    }

    /**
     * 11. 请求秤固件升级， 暂不提供
     */
    private void requestScaleFirmwareUpgrade() {
        if (weightDataHandler != null) {
            FirmwareUpgrader.requestFirmwareUpgrade(FileType.SCALE_FIRMWARE);
        }
    }

    /**
     * 12. 请求蓝牙固件升级， 暂不提供
     */
    private void requestBleFirmwareUpgrade() {
        if (weightDataHandler != null) {
            FirmwareUpgrader.requestFirmwareUpgrade(FileType.BLE_FIRMWARE);
        }
    }


    /**
     * 是否已连接
     *
     * @return
     */
    public boolean isConnected() {
        return mConnectStatus == ConnectStatus.CONNECTED;
    }

    private boolean isRegisterScreenStatusReceiver = false;
    /**
     * 注册息屏监听广播
     */
    private void registSreenStatusReceiver() {
        IntentFilter screenStatusIF = new IntentFilter();
        screenStatusIF.addAction(Intent.ACTION_SCREEN_ON);
        screenStatusIF.addAction(Intent.ACTION_SCREEN_OFF);
        mActivity.registerReceiver(mScreenStatusReceiver, screenStatusIF);
        isRegisterScreenStatusReceiver = true;
    }


    private IDeviceConnectCallback scanResultCallback = new IDeviceConnectCallback() {

        @Override
        public void onDiscovered(BluetoothDevice device) {
            ULog.i(TAG, "-----onDiscovered------name = " + device.getName() + ", Addr = " + device.getAddress());
            if (mScanResultCallback != null) {
                mScanResultCallback.onDiscovered(device);
            }
        }

        @Override
        public void onDisConnected() {
            ULog.i(TAG, "-----onDisConnected------");
            mConnectStatus = ConnectStatus.DISCONNECTED;
            if (mConnectCallback != null) {
                mConnectCallback.onDisConnected();
            }
        }

        @Override
        public void onDeviceConnected() {
            ULog.i(TAG, "-----onDeviceConnected------");
            if (btMsgListener != null) {
                btMsgListener.stopScanDevice();
            }
            mConnectStatus = ConnectStatus.CONNECTED;
//            //连接成功后，发送同步时钟到秤端
//            weightDataHandler.sendSyncSystemClock();
            if (mConnectCallback != null) {
                mConnectCallback.onConnected(curDevice);
            }
//            //请求查询固件版本
//            instance.requestFirmwareVersion();
        }

        @Override
        public void onScaleWake() {
            ULog.i(TAG, "-----onScaleWake------");
            // TODO  秤被唤醒后，需重新发送用户信息到秤
            if (mConnectCallback != null) {
                mConnectCallback.onScaleWake();
            }
            //下发用户信息
            sendUserInfo(curUser);
        }

        @Override
        public void onScaleSleep() {
            ULog.i(TAG, "-----onScaleSleep------");
            if (mConnectCallback != null) {
                mConnectCallback.onScaleSleep();
            }
        }

        @Override
        public void onBindSuccess() {
            ULog.i(TAG, "-----onBindSuccess------");
        }

    };

    public enum ConnectStatus {

        /**
         * 已连接
         */
        CONNECTED,

        /**
         * 正在连接
         */
        CONNECTING,

        /**
         * 已断开
         */
        DISCONNECTED;
    }


    /**
     * 监听息屏广播
     */
    BroadcastReceiver mScreenStatusReceiver = new BroadcastReceiver() {
        String SCREEN_ON = "android.intent.action.SCREEN_ON";
        String SCREEN_OFF = "android.intent.action.SCREEN_OFF";

        @Override
        public void onReceive(Context context, Intent intent) {
            if (SCREEN_ON.equals(intent.getAction())) {
                ULog.i(TAG, "-----SCREEN_ON-----startConnect");
                if (instance.curDevice != null) {
                    instance.startConnect(instance.curDevice);
                }
            } else if (SCREEN_OFF.equals(intent.getAction())) {
                instance.disConnectDevice();
                ULog.i(TAG, "-----SCREEN_OFF-----disConnectDevice");
            }
        }
    };


    /**
     * 在Activity的Destroy方法中必须调用此方法，否则可能导致内存泄露
     * <p>
     * 释放蓝牙模块资源的方法
     */
    public void releaseOnActivityDestroy() {
        //注销广播
        if (isRegisterScreenStatusReceiver&&mActivity != null) {
            isRegisterScreenStatusReceiver=false;
            try {
                mActivity.unregisterReceiver(mScreenStatusReceiver);
            }catch (Exception e){e.printStackTrace();}
            mActivity = null;
        }


        //断开连接
        disConnectDevice();

        mConnectCallback = null;
        mScanResultCallback = null;

        //释放其他资源
        mWeightMessage.release();
        weightDataHandler.release();
        btMsgListener.release();

        //释放升级程序
        FirmwareUpgrader.release();

    }


}
